<template>
  <div class="outbox">
    <h2>
      学生成绩
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog"
        >添加</el-button
      >
    </h2>
    <div class="filters">
      <el-select
        v-model="selectedTerm"
        placeholder="选择学期"
        style="width: 30%"
      >
        <el-option label="全部学期" value=""></el-option>
        <el-option
          v-for="term in terms"
          :key="term"
          :label="term"
          :value="term"
        ></el-option>
      </el-select>
      <!-- 以搜索形式选择学生 -->
      <el-input
        v-model="selectedStudent"
        placeholder="搜索学生姓名/学号"
        style="width: 30%"
      ></el-input>
      <!-- 以搜索形式选择课程 -->
      <el-input
        v-model="selectedCourse"
        placeholder="搜索课程"
        style="width: 30%"
      ></el-input>
    </div>
    <el-table :data="filteredScores" style="width: 100%">
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column prop="studentName" label="姓名"></el-table-column>
      <el-table-column prop="studentId" label="学号"></el-table-column>
      <el-table-column prop="semesterName" label="开课学期"></el-table-column>
      <el-table-column prop="courseName" label="课程名称"></el-table-column>
      <el-table-column prop="score" label="成绩"></el-table-column>
      <el-table-column fixed="right" width="150" label="操作">
        <template slot-scope="scope">
          <div class="buttons">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize"
        :page-sizes="pageSizes"
        :total="tablePage.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div> -->
    <el-dialog
      :title="isAdd ? '添加成绩' : '修改成绩'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        ref="formData"
        :model="formData"
        label-width="80px"
        :rules="formRules"
      >
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="formData.studentName"
            maxlength="30"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="formData.studentId"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="开课学期" prop="semesterName">
          <el-autocomplete
            v-model="formData.semesterName"
            :fetch-suggestions="querySearchTerm"
          >
          </el-autocomplete>
          <!-- <el-input v-model="formData.semesterName"></el-input> -->
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-autocomplete
            v-model="formData.courseName"
            :fetch-suggestions="querySearchCourse"
          >
          </el-autocomplete>
          <!-- <el-input v-model="formData.courseName"></el-input> -->
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input v-model="formData.score"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="saveEdit" type="primary">保存</el-button>
        <!-- <el-button v-show="isAdd" type="primary" @click="handleAdd"
          >添加</el-button
        >
        <el-button v-show="!isAdd" type="primary" @click="handleChange"
          >修改</el-button
        > -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.fetchScoreDate();
  },
  computed: {
    filteredScores() {
      // 根据选中的学期和课程筛选成绩数据
      return this.studentScores.filter((score) => {
        return (
          (!this.selectedTerm || score.semesterName === this.selectedTerm) &&
          (!this.selectedCourse ||
            score.courseName.includes(this.selectedCourse)) &&
          (!this.selectedStudent ||
            score.studentId.includes(this.selectedStudent) ||
            score.studentName.includes(this.selectedStudent))
        );
      });
    },
  },
  data() {
    return {
      input: "",
      isAdd: true,
      formData: {
        gradeId: "",
        studentName: "",
        studentId: "",
        semesterName: "",
        courseName: "",
        score: "",
      },
      dialogVisible: false,
      selectedStudent: "",
      selectedCourse: "", //搜索的课程
      selectedTerm: "", // 选中的学期
      terms: [], // 学期选项
      courses: [], // 课程选项
      studentScores: [],
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      pageSizes: [10, 20, 30],

      tableData: [],
      search: "",
      formRules: {
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        studentId: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          {
            pattern: /^[0-9]{1,20}$/,
            message: "学号必须是数字，最长20位",
            trigger: "blur",
          },
        ],
        semesterName: [
          { required: true, message: "开课学期不能为空", trigger: "blur" },
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
        ],
        score: [
          { required: true, message: "成绩不能为空", trigger: "blur" },
          {
            pattern: /^(?:100|\d{1,2})$/,
            message: "成绩必须在0-100之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    saveEdit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 校验通过，执行保存或添加操作
          if (this.isAdd) {
            // 添加成绩
            this.handleAdd();
          } else {
            // 修改成绩
            this.handleChange();
          }
        } else {
          // 校验不通过，不执行保存或添加操作
          this.$message.error("表单校验不通过，请检查输入！");
        }
      });
    },
    cancel() {
      this.formData = {
        gradeId: "",
        studentName: "",
        studentId: "",
        semesterName: "",
        courseName: "",
        score: "",
      };
      this.dialogVisible = false;
    },
    querySearchTerm(queryString, cb) {
      // 这里是获取匹配数据的逻辑，通常是从服务器获取数据
      // 例如，你可以调用一个 API 来获取数据
      // 然后调用回调函数 cb 来返回数据
      var results = this.terms.map((term) => ({
        value: term,
        semesterName: term,
      }));
      results = results.filter((result) =>
        result.semesterName.includes(queryString)
      );
      // 调用回调函数返回建议列表
      cb(results);
    },
    querySearchCourse(queryString, cb) {
      var results = this.courses.map((course) => ({
        value: course,
        courseName: course,
      }));
      results = results.filter((result) =>
        result.courseName.includes(queryString)
      );
      // 调用回调函数返回建议列表
      cb(results);
    },
    fetchData() {
      const { pageNum, pageSize } = this.tablePage;
      // 发送分页请求到后端
      // 你可以使用 axios 或其他 HTTP 请求库
      // 在请求参数中包括页码和每页条数
      // 例如，使用 axios 发送 GET 请求：
      this.$http
        .get(`/grades/page?pageNum=${pageNum}&pageSize=${pageSize}`)
        .then((response) => {
          // 处理后端返回的分页数据
          const { records, total } = response.data;
          this.studentScores = records; // 更新数据
          this.tablePage.total = total; // 更新总记录数
        })
        .catch((error) => {
          console.error("Error fetching grades:", error);
        });
    },
    // 打开添加成绩对话框
    openAddDialog() {
      this.formData = {
        gradeId: "",
        studentName: "",
        studentId: "",
        semesterName: "",
        courseName: "",
        score: "",
      };
      this.isAdd = true;
      this.dialogVisible = true;
    },
    fetchScoreDate() {
      this.$http
        .get(`/grades/all`)
        .then((res) => {
          this.studentScores = res.data;
          // 获取所有学期并去重
          const uniqueTerms = [
            ...new Set(res.data.map((score) => score.semesterName)),
          ];
          this.terms = uniqueTerms;

          const uniqueCourses = [
            ...new Set(res.data.map((score) => score.courseName)),
          ];
          this.courses = uniqueCourses;
        })
        .catch((error) => {
          console.error("get student's grades error");
        });
    },
    handleAdd() {
      // 发送添加的请求
      this.$http
        .post(`/grades/add`, this.formData)
        .then((response) => {
          // 处理成功响应，可以刷新列表等操作
          this.$message.success("添加成功");
          this.fetchScoreDate();
          this.dialogVisible = false; // 关闭添加对话框
          this.formData = {}; //清空数据
        })
        .catch((error) => {
          console.error("Error adding garde:", error);
          this.$message.error("添加失败，该记录已存在");
        });
    },
    handleChange() {
      // 发送更新的请求
      this.$http
        .put(`/grades/update`, this.formData)
        .then((response) => {
          // 处理成功响应，可以刷新列表等操作
          this.$message.success("修改成功");
          this.fetchScoreDate();
          this.dialogVisible = false; // 关闭添加对话框
          this.formData = {}; //清空数据
        })
        .catch((error) => {
          console.error("Error changing garde:", error);
          this.$message("修改失败");
        });
    },
    handleEdit(index, row) {
      this.isAdd = false;
      this.formData = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    handleDelete(index, row) {
      let id = row.gradeId;
      this.$confirm("确定要删除这条记录吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮，调用deleteGrade方法
          this.deleteGrade(id);
        })
        .catch(() => {
          // 用户点击了取消按钮，不做任何操作
        });
    },
    deleteGrade(id) {
      this.$http
        .delete(`/grades/delete/${id}`)
        .then((response) => {
          // 删除成功后刷新数据
          this.fetchScoreDate();
          this.$message.success("删除成功");
        })
        .catch((error) => {
          console.error("Error deleting grade:", error);
          this.$message.error("删除出错");
        });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      // 在此刷新数据
    },
  },
};
</script>
<style scoped>
h2 {
  display: flex;
  justify-content: space-between;
}
.outbox {
  margin: 20px;
}
.buttons {
  display: flex;
  justify-content: space-around;
}
.filters {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.pagination {
  margin-top: 30px;
  text-align: center;
}
</style>